package znet

import (
	"bytes"
	"encoding/binary"
	"errors"

	"github.com/desyang-hub/zinx_demo/utils"
	"github.com/desyang-hub/zinx_demo/zface"
)

type DataPack struct {
}

// 定义包头长度
func (dp *DataPack) GetHeadLen() uint32 {
	return 8
}

// 封包
func (dp *DataPack) Pack(msg zface.IMessage) ([]byte, error) {
	// 创建一个缓冲
	dataBuf := bytes.NewBuffer([]byte{})

	// 写入一个DataLen
	if err := binary.Write(dataBuf, binary.LittleEndian, msg.GetMsgLen()); err != nil {
		return nil, err
	}

	// 写入一个MsgID
	if err := binary.Write(dataBuf, binary.LittleEndian, msg.GetMsgID()); err != nil {
		return nil, err
	}

	// 写入一个MsgData
	if err := binary.Write(dataBuf, binary.LittleEndian, msg.GetMsgData()); err != nil {
		return nil, err
	}

	return dataBuf.Bytes(), nil
}

// 拆包
func (dp *DataPack) UnPack(buf []byte) (zface.IMessage, error) {
	dataReader := bytes.NewReader(buf)

	msg := &Message{}

	// 读取长度
	if err := binary.Read(dataReader, binary.LittleEndian, &msg.MsgLen); err != nil {
		return nil, err
	}

	if utils.AppContext.MaxPackagesSize > 0 && utils.AppContext.MaxPackagesSize < msg.MsgLen {
		return nil, errors.New("msg len always extend MaxPakcagesSize")
	}

	// 读取ID
	if err := binary.Read(dataReader, binary.LittleEndian, &msg.MsgID); err != nil {
		return nil, err
	}

	return msg, nil
}

func NewDataPack() (dp *DataPack) {
	return &DataPack{}
}
